package com.jadows.tdog.state;

import cn.hutool.core.util.RandomUtil;
import com.jadows.tdog.constants.CacheConstants;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 在线用户注册表
 *
 * @author taojiacheng
 */
@Service
public class OnlineUserRegister {

    final RedissonClient redissonClient;

    final static String instanceId = RandomUtil.randomString(12);

    public OnlineUserRegister(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public void register(String uid) {
        // add uid -> instanceIds
        RSet<String> set = redissonClient.getSet(CacheConstants.ONLINE_USER_REGISTER + uid);
        set.add(instanceId);
    }

    public void unregister(String uid) {
        // 如果当前用户在此服务器上还有channel, 则不注销
        if (SimpleWSSessionUtil.isCurrentServer(uid)) {
            return;
        }
        // remove uid -> instanceIds
        RSet<String> set = redissonClient.getSet(CacheConstants.ONLINE_USER_REGISTER + uid);
        set.remove(instanceId);
    }

    public boolean isOnline(String uid) {
        RSet<String> set = redissonClient.getSet(CacheConstants.ONLINE_USER_REGISTER + uid);
        return set.contains(instanceId);
    }


    public Set<String> getUserInstanceId(String uid) {
        RSet<String> set = redissonClient.getSet(CacheConstants.ONLINE_USER_REGISTER + uid);
        return set.readAll();
    }


    public String getCurrentInstanceId() {
        return instanceId;
    }

}
